import browserPool from "../spider/browserPool.js";
import {strToNumber} from "./utils.js";

const RETRY_TiME = 4;
export const getCoinPriceSpider = async (unicode, platform, selector, retryTime = 0) => {
  if (retryTime > RETRY_TiME) {
    return {
      result: false
    };
  }
  let browser = await browserPool.getBrowser();
  let page = await browserPool.getBrowserPageWithoutPicAndVideo(browser);
  try {
    let url = platform + unicode;
    console.log('url', url);
    // 超时时间20秒
    await page.goto(url, {waitUntil: 'networkidle0', timeout: 20 * 1000});
    await page.waitForSelector(selector, {timeout: 20 * 1000});
    const price = await page.$eval(selector, (item) => {
      return item.innerHTML;
    });
    await browserPool.backBrowser(browser);
    // console.log('price', price, unicode);
    return {
      price: strToNumber(price),
      result: true
    };
  } catch (e) {
    // 出现错误 重试
    console.log(e.message, '获取' + unicode + '价格失败');
    await browserPool.browserUpdate(browser);
    return await getCoinPriceSpider(unicode, platform, selector, retryTime + 1);
  }
};
